<?php
/**
 * Created by PhpStorm.
 * User: Neho
 * Date: 2018/2/23
 * Time: 11:34
 */

namespace app\api\logic;

use think\Model;
use \think\Loader;
use app\common\model\User as UserModel;
use app\common\utils\Encrypt as EncryptUtil;

class UserEntry extends Model
{
    protected $userModel;

    protected function initialize()
    {
        parent::initialize();
        $this->userModel = Loader::model('User', 'model');
    }

    /**
     * 用户注册
     * @param array $val 用户注册帐号信息
     * @return array
     * @throws
     */
    public function regist($val)
    {
        $isRegist = $this->userModel->isRegist($val['account']);
        if (!$isRegist) {
            $this->startTrans();
            try {
                $this->userModel->user_sex = 1;
                if ($this->userModel->save()) {
                    $auth = [
                        'identity_type' => 1,
                        'identifier' => $val['account'],
                        'credential' => EncryptUtil::password($val['password']),
                    ];
                    if ($this->userModel->userAuth()->save($auth)) {
                        $this->commit();
                        $data = array(
                            'userId' => $this->userModel->id
                        );
                        return $data;
                    }
                }
            } catch (\Exception $e) {
                $this->rollback();
            }
        } else {
            //  该用户已经注册
        }
    }

    /**
     * 用户登录
     * @param array $val 用户登录信息
     * @return String | array
     * @throws
     */
    public function login($val)
    {
        $encryptPassword = EncryptUtil::password($val['password']);
        $user = UserModel::hasWhere('userAuth', ['identifier' => $val['account'], 'credential' => $encryptPassword])->find();
        if (isset($user)) {
            $data = [
                'userId' => $user->id,
            ];
            return $data;
        }
        return '用户或密码错误';
    }
}
